package com.atguigu.gmall.item.controller;

import com.atguigu.gmall.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class RedissonController {

    @Autowired
    RedissonClient redissonClient;

    String x = "abc";



    /**
     * 闭锁
     */
    @GetMapping("/shenlong")
    public Result shenlong() throws InterruptedException {
        RCountDownLatch countDownLatch = redissonClient.getCountDownLatch("qilongzhu");
        countDownLatch.trySetCount(7L);
        log.info("等待召唤");
        countDownLatch.await();
        return Result.ok("神龙。。。");
    }

    @GetMapping("/longzhu")
    public Result longzhu() {
        RCountDownLatch qilongzhu = redissonClient.getCountDownLatch("qilongzhu");
        qilongzhu.countDown();
        return Result.ok("1颗到手");
    }


    /**
     * 读写锁 只有读读无锁，其它都是有锁
     */
    @GetMapping("/write")
    public Result write() {
        //1、获取读写锁
        RReadWriteLock rwLock = redissonClient.getReadWriteLock("rwLock");

        //2、获取写锁
        RLock wLock = rwLock.writeLock();

        //3、加写锁
        try {
            wLock.lock();
            log.info("业务正在进行数据修改....");
            TimeUnit.SECONDS.sleep(15);
            x = UUID.randomUUID().toString();
            log.info("业务数据修改完成....");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return Result.ok(x);

    }

    @GetMapping("/read")
    public Result Read(){
        //1、获取读写锁
        RReadWriteLock rwLock = redissonClient.getReadWriteLock("rwLock");

        //2、获取读锁
        RLock lock = rwLock.readLock();

        //3、加读锁
        try {
            lock.lock();
            log.info("业务正在远程读取数据中....");
            TimeUnit.SECONDS.sleep(10);
            log.info("业务远程读取数据完成....");
        } catch (InterruptedException e) {


        } finally {
            lock.unlock();
        }

        return Result.ok(x);
    }


    @GetMapping("/redisson/lock")
    public Result lock() {
        RLock lock = redissonClient.getLock("hahaha");
        try{
            lock.lock();//加解锁一定成对出现
            log.info("加锁后，进行业务操作");
            TimeUnit.SECONDS.sleep(20);
            log.info("加锁执行成功");
        }catch (Exception e){

        }finally {
            try{
                lock.unlock();
            }catch (Exception e){

            }
            log.info("解锁完成");
        }

        return Result.ok();


    }


    @GetMapping ("/redisson/client")
    public Result client() {
        log.info("redisson={}",redissonClient);
        return Result.ok();
    }

}
